package mroute

import (
	"github.com/gin-gonic/gin"
	"mygo/mystruct"
	"mygo/mymongo"
	"path/filepath"
	"os"
	"mygo/global"
)

// 日志
func MyLogApi(cont *gin.Context) {
	model := cont.Query("model")
	path  := cont.DefaultQuery("path", "")

	user := mymongo.Get_Chcae_User(cont.GetHeader("UserNameBoot"), global.Mtoken.Key)
	if user == nil {
		cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "没有权限[用户未登录]"})
		return
	}
	if user.Standing <= mystruct.AUTH_Superadmin {
		cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "权限不足"})
		return
	}
	mlog_path := filepath.Join(global.Mtoken.Log_Path, path)
	switch model {
		case "get":
			if path == "" {
				page := cont.DefaultQuery("page", "1")
	            page_size := cont.DefaultQuery("pagesize", "100")
	            path_list, err := mystruct.ListFilesInSegments(global.Mtoken.Log_Path, mystruct.StrToInt64(page), mystruct.StrToInt64(page_size))
	            if err == nil {
	            	cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": path_list})
	            	return
	            }
	            cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": err.Error()})
	            return
			}
			if mystruct.Exists(mlog_path) && mystruct.IsFile(mlog_path) {
				if mystruct.IsFileLargerThan(mlog_path, 200*1024*1024) {
					cont.JSON(mystruct.StatusUnauthorized, gin.H{"error": "文件大于200BM网页不显示"})
					cont.Abort()
					return
				} 
				cont.File(mlog_path)
				return
			}
			cont.JSON(mystruct.StatusNotFound, gin.H{"code": mystruct.MyCodeErr, "msg": "文件不存在"})
			
		case "del":
			if mystruct.Exists(mlog_path) && mystruct.IsFile(mlog_path) {
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": os.RemoveAll(mlog_path)})
				return
			}
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "文件不存在"})
			
		default:
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "参数错误"})
	}
}